<?php


namespace app\common\model;

use think\Model;

class Cart extends Model {
    var $userId;
    function __construct() {
        //获取user_id
        if (is_null($this->userId)) {
            $userId = $this->userId = model('user')->getUserId();
        } else {
            $userId = $this->userId;
        }
        if (!$userId) {
            return;
        }
    }

    private function getProductClass($class) {
        $config=getConfig('product');
        foreach ($config as $k => $v) {
            if (is_numeric($class)) {
                if ($v['id'] == $class) {
                    $classInfo = $k;
                    return $classInfo;
                }
            } else {
                if ($k == $class) {
                    $classInfo = $v['id'];
                    return $classInfo;
                }
            }
        }
    }
    //新增预购清单
    function add($demand,$detail_id,$amount = 1){
        $user_id = $this->userId;
        if(!$user_id){
            return array('state'=>0,'errormsg'=>'请登录');
        }
        if (!$detail_id){
            return [
                'state' => 0,
                'errormsg' => '参数错误'
            ];
        }
        //查询是否添加过
        $cart_info = db('cart')->where("detail_id = $detail_id and user_id = $this->userId and state = 1")->find();
        if($cart_info) {
            db('cart')->where("detail_id = $detail_id and user_id = $this->userId")->setInc('amount');
            return array('state'=>1,'errormsg'=>'添加成功');
        }
        $class = getConfig('product')[$demand]['id'];
        $data['detail_id'] = $detail_id;
        $data['user_id'] = $user_id;
        $data['amount'] = $amount;
        $data['state'] = 1;
        $data['class'] = $class;
        $data['create_time'] = $_SERVER['REQUEST_TIME'];
        $res = db('cart')->insert($data);
        if(!$res) return ['state'=>0,'errormsg'=>'添加失败'];
        return array('state'=>1,'errormsg'=>'添加成功');
    }

    public function setNum($detail_id,$amount)
    {
        $user_id = $this->userId;
        if(!$user_id){
            return array('state'=>0,'errormsg'=>'请登录');
        }
        if(!$detail_id){
            return array('state'=>0,'errormsg'=>'参数错误');
        }
        $res = db('cart')->where("cart_id = $detail_id and state = 1")->update(['amount'=>$amount]);
        if(!$res){
            return array('state'=>0,'errormsg'=>'修改失败');
        }
        return array('state'=>1,'errormsg'=>'修改成功');
    }
    //删除清单中的商品
    function remove($detail_id){
        $user_id =$this->userId;
        //判断输入数据
        if (!$user_id) {
            return array('state' => 0, 'errormsg' => '没找到当前用户', 'errorcode' => '');
        }
        //判断输入数据
        if (!$detail_id) {
            $data['state'] = 0;
            $where = "user_id = '$user_id' and state = '1'";
            $res = db('cart')->where($where)->update($data);
            if (!$res) {
                return array('state' => 0, 'errormsg' => '删除失败');
            }
            return array('state' => 1, 'errormsg' => 'ok');
        }
        $where = "detail_id = '$detail_id' and user_id = '$user_id' and state = 1";
        if (!db('cart')->where($where)->find()) {
            return array('state' => 0, 'errormsg' => '未找到');
        }
        $data['state'] = 0;
        $result = db('cart')->where($where)->update($data);
        if (!$result) {
            return array('state' => 0, 'errormsg' => '保存失败');
        }
        return array('state' => 1, 'errormsg' => '删除成功');
    }

//    //清空cart
//    function remove(){
//        $user_id = $this->userId;
//        if (!$user_id) {
//           return array('state' => 0, 'errormsg' => 'user_id not find', 'errorcode' => '');
//        }
//        $data['state'] = 0;
//        $where = "user_id = '$user_id' and state = '1'";
//        $res = db('cart')->where($where)->update($data);
//        if (!$res) {
//            return array('state' => 0, 'errormsg' => 'remove incorrect', 'errorcode' => '');
//        }
//        return array('state' => 1, 'errormsg' => 'ok', 'errorcode' => '');
//    }

    //获取list列表
    function getList($filter){
        $user_id = $this->userId;
        if (!$user_id) {
           return array('state' => 0, 'errormsg' => '未找到用户', 'errorcode' => '');
        }
        $demand = $filter['demand'];
        if(!$demand){
            return array('state' => 0, 'errormsg' => '未找到类别', 'errorcode' => '');
        }
        if ($filter['page'] != '') {
            $pages = $filter['page']-1;
        } else {
            $pages = 0;
        }
        if ($filter['maxPerPage'] != '') {
            $maxPerPage = $filter['maxPerPage'];
        } else {
            $maxPerPage = 12;
        }
        $where=  "state = '1' and user_id = '$user_id'";
        //匹配demand
        $class = $this->getProductClass($demand);
        $where .= " and class = '$class'";
        if ($filter['keywords']) {
            $where .= " and (d.name like '%$filter[keywords]%')";
        }
        $cart = db('cart')->where($where)->limit($pages * $maxPerPage, $maxPerPage)->select();
        if(!$cart){
            return array('state' =>1, 'data' => []);
        }
        $demand_id = $demand.'_id';
        $list = [];
        foreach ($cart as $k => $v){
            $list[] = db($demand.'_detail')->alias('dd')
                     ->field('name,price,imgurls,labels,d.mall_id,deposit,discount,discount_price,detail_id,d.state')
                     ->join("$demand d","d.$demand_id = dd.$demand_id")
                     ->where("dd.detail_id = $v[detail_id]")->order('d.create_time desc')
                     ->find();
        }

        foreach ($list as $k=>$v){
            if(!$v){
                return array('state'=>1,'data'=>[]);
            }

            //计算实际金额
            if (!$v['price'] or $v['state'] != 1) {
                return [
                    'state' => 0,
                    'errormsg' => '价格输入错误'
                ];
            }
            foreach ($cart as $kk =>$vv){
                if($v['detail_id'] == $vv['detail_id']){
                    $list[$k]['amount'] = $vv['amount'];
                }
            }

            $num = $list[$k]['amount'];
            if($v['deposit']){
                $list[$k]['disconut_fee'] = 0;
                $list[$k]['total_fee'] = $num * $v['deposit'];
            }else{
                if($v['discount']) {
                    $v['discount'] ? $v['discount'] : $v['discount'] = 100;
                    $list[$k]['total_fee'] = $num * ($v['price'] * ($v['discount'] / 100));
                    $price_old = $num * $v['price'];
                    $list[$k]['disconut_fee'] = $list[$k]['discount_fee'] = $price_old - $num * ($v['price'] * ($v['discount'] / 100));
                }elseif(!$v['discount'] && $v['discount_price']){
                    $list[$k]['total_fee'] = $num * ($v['price'] - $v['discount_price']);
                    $price_old = $num * $v['price'];
                    $list[$k]['disconut_fee'] = $list[$k]['discount_fee'] = $price_old-$num * ($v['price'] - $v['discount_price']);

                }else{
                    $list[$k]['total_fee'] = $num *$v['price'];
                    $price_old = $num *$v['price'];
                    $list[$k]['disconut_fee'] = 0;
                    $list[$k]['product'] = 1;
                }
            }
            $list[$k]['total_fee_product'] = $num * $v['price'];
            $detail_option = db('mall_detail_option')
                ->where("detail_id = $v[detail_id] and state = 1")
                ->field('detail_id,detail_option_id,option_name_cn,option_name_en,config_id')->select();
            foreach ($detail_option as $key => $values){
                if($values['detail_id'] == $v['detail_id'] && !empty($values['config_id'])){
                    $config = db('mall_config')->field('config_id,config_name_cn,config_name_en')->where("config_id = $values[config_id]")->find();
                    if($values['config_id'] == $config['config_id']){
                        $detail_option[$key]['config_name_cn'] = $config['config_name_cn'];
                        $detail_option[$key]['config_name_en'] = $config['config_name_en'];
                    }
                    $list[$k]['options'][] = $detail_option[$key];
                }
            }
            if(strpos($v['imgurls'],',')) {
                $list[$k]['imgurl'] = strstr($v['imgurls'], ',', true);  // 从 PHP 5.3.0 起
            }else{
                $list[$k]['imgurl'] = $v['imgurls'];
            }
            unset($list[$k]['homepage'],$list[$k]['highlight'],$list[$k]['suggest'],$list[$k]['range'],$list[$k]['state'],$list[$k]['detail_code'],$list[$k]['highlight']);
        }
        $pages = $pages + 1;
        $cart = db('cart')->where($where)->limit($pages * $maxPerPage, $maxPerPage)->select();
        if(count($cart)){
            $more = 1;
        }else{
            $more = 0;
        }
        $res = array('state'=>1,'data'=>array('list' => $list), 'more' => $more, 'maxPerPage' => $maxPerPage);
        return $res;
        //输出数据处理
    }

    public function amount()
    {
        if(!$this->userId) return ['state'=>1,'data'=>['amount'=>0]];
//        $res = db('cart')->field('sum(amount) as amount')->where("user_id = $this->userId and state = 1")->select();
        $res = db('cart')->field('detail_id')->where("user_id = $this->userId and state = 1")->select();
        //判断价格是否存在
        $detail_id = [];
        foreach ($res as $k =>$v){
            if($v){
                $detail_id[] = $v['detail_id'];
            }

        }
        $detail_id = implode(',',$detail_id);
        if(!$detail_id){
            return ['state'=>1,'data'=>['amount'=>0]];
        }
        $list = db('mall_detail')->alias('dd')
            ->join("mall d","d.mall_id = dd.mall_id")
            ->where("dd.detail_id in ($detail_id)")->order('d.create_time desc')
            ->count();
        return ['state'=>1,'data'=>['amount'=>$list]];
    }
}
